<template>
  <div class="key-personnel">
    <el-card>
      <template #header>
        <div class="card-header">
          <span>重点人口管理</span>
          <el-button type="primary" @click="showInputDialog = true">
            <el-icon><Plus /></el-icon>
            录入重点人口
          </el-button>
        </div>
      </template>
      
      <!-- 查询区域 -->
      <div class="search-section">
        <el-form :model="searchForm" inline>
          <el-form-item label="姓名">
            <el-input v-model="searchForm.name" placeholder="请输入姓名" clearable style="width: 200px" />
          </el-form-item>
          <el-form-item label="身份证号">
            <el-input v-model="searchForm.idCard" placeholder="请输入身份证号" clearable style="width: 200px" />
          </el-form-item>
          <el-form-item label="重点人员类别">
            <el-select v-model="searchForm.category" placeholder="请选择类别" clearable style="width: 160px">
              <el-option label="涉毒人员" value="涉毒人员" />
              <el-option label="涉恐人员" value="涉恐人员" />
              <el-option label="涉稳人员" value="涉稳人员" />
              <el-option label="精神病患者" value="精神病患者" />
              <el-option label="刑满释放人员" value="刑满释放人员" />
              <el-option label="社区矫正人员" value="社区矫正人员" />
              <el-option label="吸毒人员" value="吸毒人员" />
              <el-option label="肇事肇祸精神病人" value="肇事肇祸精神病人" />
              <el-option label="重点上访人员" value="重点上访人员" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-form-item>
          <el-form-item label="风险等级">
            <el-select v-model="searchForm.riskLevel" placeholder="请选择风险等级" clearable style="width: 120px">
              <el-option label="低风险" :value="1" />
              <el-option label="中风险" :value="2" />
              <el-option label="高风险" :value="3" />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleSearch">
              <el-icon><Search /></el-icon>
              查询
            </el-button>
            <el-button @click="handleReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 数据表格 -->
      <el-table 
        :data="tableData" 
        v-loading="loading"
        stripe
        border
        style="width: 100%"
      >
        <el-table-column prop="name" label="姓名" width="100" />
        <el-table-column prop="idCard" label="身份证号" width="180" />
        <el-table-column prop="category" label="重点人员类别" width="120" />
        <el-table-column prop="riskLevel" label="风险等级" width="100">
          <template #default="scope">
            <el-tag 
              :type="getRiskLevelType(scope.row.riskLevel)"
              size="small"
            >
              {{ getRiskLevelText(scope.row.riskLevel) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="responsibleOfficer" label="责任民警" width="100" />
        <el-table-column prop="contactFrequency" label="联系频次" width="100" />
        <el-table-column prop="monitorStartDate" label="监管开始日期" width="120">
          <template #default="scope">
            {{ formatDate(scope.row.monitorStartDate) }}
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="80">
          <template #default="scope">
            <el-tag 
              :type="scope.row.status === 1 ? 'success' : 'info'"
              size="small"
            >
              {{ scope.row.status === 1 ? '在管' : '解除' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="scope">
            <div class="action-buttons">
              <el-button type="primary" size="small" @click="handleView(scope.row)">查看</el-button>
              <el-button 
                :type="scope.row.status === 1 ? 'warning' : 'info'" 
                size="small" 
                :disabled="scope.row.status === 0"
                @click="handleEdit(scope.row)"
              >
                {{ scope.row.status === 1 ? '解除监管' : '已解除' }}
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 录入对话框 -->
    <KeyPersonnelInput 
      v-model="showInputDialog"
      @success="handleInputSuccess"
    />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search } from '@element-plus/icons-vue'
import axios from 'axios'
import { API_BASE_URL } from '@/config/api'
import KeyPersonnelInput from './components/KeyPersonnelInput.vue'

const loading = ref(false)
const showInputDialog = ref(false)

// 搜索表单
const searchForm = reactive({
  name: '',
  idCard: '',
  category: '',
  riskLevel: null
})

// 表格数据
const tableData = ref([])

// 分页信息
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 获取风险等级类型
const getRiskLevelType = (level) => {
  switch (level) {
    case 1: return 'success'
    case 2: return 'warning'
    case 3: return 'danger'
    default: return 'info'
  }
}

// 获取风险等级文本
const getRiskLevelText = (level) => {
  switch (level) {
    case 1: return '低风险'
    case 2: return '中风险'
    case 3: return '高风险'
    default: return '未知'
  }
}

// 格式化日期
const formatDate = (date) => {
  if (!date) return '-'
  return new Date(date).toLocaleDateString()
}

// 查询数据
const handleSearch = () => {
  pagination.currentPage = 1
  loadData()
}

// 重置搜索
const handleReset = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = key === 'riskLevel' ? null : ''
  })
  handleSearch()
}

// 加载数据
const loadData = async () => {
  loading.value = true
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      ElMessage.error('请先登录')
      loading.value = false
      return
    }

    // 构建查询参数
    const params = {
      pageNum: pagination.currentPage,
      pageSize: pagination.pageSize
    }

    // 添加可选查询参数
    if (searchForm.name && searchForm.name.trim()) {
      params.name = searchForm.name.trim()
    }
    if (searchForm.idCard && searchForm.idCard.trim()) {
      params.idCard = searchForm.idCard.trim()
    }
    if (searchForm.category) {
      params.category = searchForm.category
    }
    if (searchForm.riskLevel !== null) {
      params.riskLevel = searchForm.riskLevel
    }

    console.log('发送重点人口查询请求，参数:', params)

    // 发送查询请求
    const response = await axios.get(`${API_BASE_URL}/key-personnel/query`, {
      params,
      headers: {
        'token': token
      }
    })

    console.log('重点人口查询响应:', response.data)

    const result = response.data
    if (result.status === 200) {
      tableData.value = result.data || []
      // 注意：后端可能需要返回总数，这里暂时使用数据长度
      pagination.total = result.data ? result.data.length : 0
    } else {
      ElMessage.error(result.msg || '查询失败')
      tableData.value = []
      pagination.total = 0
    }

  } catch (error) {
    console.error('查询重点人口数据失败:', error)
    
    if (error.response) {
      const errorMsg = error.response.data?.msg || '服务器错误，请稍后重试'
      ElMessage.error(errorMsg)
    } else if (error.request) {
      ElMessage.error('网络错误，请检查网络连接')
    } else {
      ElMessage.error('查询失败，请稍后重试')
    }
    
    tableData.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 更新重点人员状态
const updatePersonnelStatus = async (id, status) => {
  loading.value = true
  try {
    const token = localStorage.getItem('token')
    if (!token) {
      ElMessage.error('请先登录')
      loading.value = false
      return
    }

    console.log('发送重点人员状态更新请求，参数:', { id, status })

    // 发送更新请求
    const response = await axios.put(`${API_BASE_URL}/key-personnel/update`, null, {
      params: {
        id: id,
        status: status
      },
      headers: {
        'token': token
      }
    })

    console.log('重点人员状态更新响应:', response.data)

    const result = response.data
    if (result.status === 200) {
      ElMessage.success('监管状态更新成功')
      // 重新加载数据以刷新表格
      loadData()
    } else {
      ElMessage.error(result.msg || '状态更新失败')
    }

  } catch (error) {
    console.error('更新重点人员状态失败:', error)
    
    if (error.response) {
      const errorMsg = error.response.data?.msg || '服务器错误，请稍后重试'
      ElMessage.error(errorMsg)
    } else if (error.request) {
      ElMessage.error('网络错误，请检查网络连接')
    } else {
      ElMessage.error('更新失败，请稍后重试')
    }
  } finally {
    loading.value = false
  }
}

// 查看详情
const handleView = (row) => {
  ElMessage.info('查看功能待开发')
}

// 编辑 - 更改监管状态为解除
const handleEdit = (row) => {
  // 检查当前状态
  if (row.status === 0) {
    ElMessage.warning('该重点人员已经是解除状态')
    return
  }

  ElMessageBox.confirm(
    `确定要将 "${row.name}" 的监管状态更改为解除吗？`,
    '确认操作',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    await updatePersonnelStatus(row.id, 0) // 0表示解除状态
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}

// 分页大小改变
const handleSizeChange = (size) => {
  pagination.pageSize = size
  loadData()
}

// 当前页改变
const handleCurrentChange = (page) => {
  pagination.currentPage = page
  loadData()
}

// 录入成功回调
const handleInputSuccess = () => {
  ElMessage.success('重点人口录入成功')
  loadData() // 重新加载数据
}

// 组件挂载时加载数据（发送默认查询请求）
onMounted(() => {
  console.log('重点人口管理页面加载，发送默认查询请求')
  loadData()
})
</script>

<style lang="scss" scoped>
.key-personnel {
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .search-section {
    margin-bottom: 20px;
    padding: 20px;
    background-color: #f5f7fa;
    border-radius: 4px;
  }

  .pagination-container {
    margin-top: 20px;
    text-align: right;
  }

  // 操作列按钮横向排列
  .action-buttons {
    display: flex;
    align-items: center;
    gap: 8px;
    flex-wrap: nowrap;
  }
  .action-buttons :deep(.el-button) {
    white-space: nowrap;
  }
}
</style>